package com.qf.service.impl;

import com.qf.entity.MallGoodsSpecEntity;
import com.qf.entity.MallGoodsSpecOptionsEntity;
import com.qf.mapper.MallGoodsMapper;
import com.qf.service.IMallGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MallGoodsService implements IMallGoodsService {

    @Autowired
    private MallGoodsMapper mapper;

    @Override
    public List<MallGoodsSpecEntity> findAll() {
        return mapper.findAll();
    }
    @Override
    public List<MallGoodsSpecOptionsEntity> findByPage(MallGoodsSpecOptionsEntity entity) {
        return mapper.findByPage(entity);
    }

    @Override
    public int delete(String id) {
        return mapper.delete(id);
    }

    @Override
    public Map<String, Integer> add(MallGoodsSpecEntity mallGoodsSpec, List<MallGoodsSpecOptionsEntity> entity) {
        MallGoodsSpecEntity Spec = mapper.findBySpecName(mallGoodsSpec.getSpecName());
        int success = 0, errors = 0;
        for (MallGoodsSpecOptionsEntity en : entity) {
            if (mallGoodsSpec.getSpecName().equals(en.getGoodsSpec().getSpecName())) {
                if (mapper.findByOptionName(en.getOptionName()) != null) {
                    errors++;
                } else {
                    if (Spec != null) {
                        en.setSpecId(Spec.getId());
                        int i = mapper.add1(en);
                        if (i == -1) {
                            errors++;
                        } else {
                            success++;
                        }
                    } else {
                        int i = mapper.add2(mallGoodsSpec);
                        MallGoodsSpecEntity Spec2 = mapper.findBySpecName(mallGoodsSpec.getSpecName());
                        en.setSpecId(Spec2.getId());
                        int i1 = mapper.add1(en);
                        if (i == -1 && i1 == -1) {
                            errors++;
                        } else {
                            success++;
                        }
                    }
                }
            }
        }
        HashMap<String, Integer> map = new HashMap<>();
        map.put("成功", success);
        map.put("失败", errors);
        return map;
    }

    @Override
    public int update(MallGoodsSpecOptionsEntity entity) {
        return mapper.update(entity);
    }
}
